<%--
  Created by IntelliJ IDEA.
  User: Maibenben
  Date: 2020/1/7
  Time: 19:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>员工列表</title>
    <%
        pageContext.setAttribute ("path", request.getContextPath ());
    %>
    <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery，所以必须放在前边) -->
    <script src="${path}/js/jquery-3.3.1.min.js"></script>
    <link href="${path}/css/bootstrap.min.css" rel="stylesheet">
    <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
    <script src="${path}/js/bootstrap.min.js"></script>

    <script type="text/javascript">

        //总页数
        var totalPageNum;
        //当前页码
        var currentPage;

        $(function () {
            //JQuery实现全选与全不选
            $("#checkAll").bind("click", function () {
                $('input[name="check"]').each(function () {
                    $(this).prop("checked", $("#checkAll").is(":checked"));
                })
            });

            //当都被选中checkAll也自动被选中
            $(document).on("click",$('input[name="check"]'),function x() {
                var flag = $('input[name="check"]:checked').length == $('input[name="check"]').length;
                 $("#checkAll").prop("checked",flag);
            });
        });

        //页面加载完毕之后,直接去发送ajax请求，要到分页数据
        $(function () {
            //获取url请求参数
            //1.获取请求url中?及之后参数的字符串
            var search = location.search;
            // alert(search);  //?pageNum=2
            //2.分割字符串获取参数  切割字符串，拿到第二个值
            var pageNum = search.split("=")[1];


            // alert(pageNum);  //undefined
            //如果pageNum大于总页数，使pageNum
            if (pageNum == undefined) {
                pageNum = 1;
            }
            currentPage = pageNum;
            //展示页面
            showPage(pageNum);
        });

        //根据pageNum页码展示员工数据
        function showPage(pageNum) {
            $.get("${path}/employee/getAllEmp", {pageNum: pageNum}, function (result) {
                // alert(result);
                //1.解析并显示员工数据
                build_emps_table(result.data);
                //2.解析并显示分页信息
                build_page_info(result.data);
                //3.解析并显示分页条数据
                build_page_nav(result.data);
            });

            //解析并显示员工数据
            function build_emps_table(data) {
                var nodes = "";
                for (var i = 0; i < data.pageInfo.list.length; i++) {
                    var employee = data.pageInfo.list[i];
                    var node = '<tr>\n' +
                        '                <td><input type="checkbox" name="check"></td>\n' +
                        '                <td>' + employee.empId + '</td>\n' +
                        '                <td>' + employee.empName + '</td>\n' +
                        '                <td>' + employee.gender + '</td>\n' +
                        '                <td>' + employee.email + '</td>\n' +
                        '                <td>' + employee.department.deptId + '</td>\n' +
                        '                <td>' + employee.department.deptName + '</td>\n' +
                        '                <td>\n' +
                        '                    <button type="button" edit_emp_id="' + employee.empId + '" class="btn btn-success btn-sm editEmp" href="#">\n' +
                        '                        <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> 编辑\n' +   //为编辑按钮添加一个自定义属性，该属性等于员工id
                        '                    </button>\n' +
                        '                    <button type="button" del_emp_id="' + employee.empId + '" class="btn btn-danger btn-sm delEmp" onclick="delEmp(' + employee.empId + ',this);">\n' +
                        '                        <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除\n' +   //为删除按钮添加一个自定义属性，该属性等于员工id
                        '                    </button>\n' +
                        '                </td>\n' +
                        '\n' +
                        '            </tr>';
                    nodes += node;
                }
                $("#tbody").html(nodes);
            }

            // 解析并显示分页信息
            function build_page_info(data) {
                var node = '当前第 <a class="btn" style="background-color: black;color: white" disabled="disabled">' + data.pageInfo.pageNum + '</a> 页,\n' +
                    '        共有<a class="btn" style="background-color: black;color: white" disabled="disabled">' + data.pageInfo.pages + '</a>页，\n' +
                    '        总计<a class="btn" style="background-color: black;color: white" disabled="disabled">' + data.pageInfo.total + '</a>条记录';
                $("#page_info").html(node);

                //把总页码赋予totalPageNum
                if (data.pageInfo.total % data.pageInfo.pageSize == 0) {
                    totalPageNum = data.pageInfo.pages + 1;
                } else {
                    totalPageNum = data.pageInfo.pages;
                }

            }

            //解析并显示分页条数据
            function build_page_nav(data) {
                var lis = "";
                //首页
                var firstPageLi = '<li><a href="${path}/index.jsp?pageNum=1">首页</a></li>';
                //上一页
                var beforePageNum = data.pageInfo.pageNum - 1 > 0 ? data.pageInfo.pageNum - 1 : 1;
                var beforePageLi = '<li>\n' +
                    '                    <a href="${path}/index.jsp?pageNum=' + beforePageNum + '"\n' +
                    '                       aria-label="Previous">\n' +
                    '                        <span aria-hidden="true">&laquo;</span>\n' +
                    '                    </a>\n' +
                    '                </li>';

                lis += firstPageLi;
                lis += beforePageLi;

                //页码
                for (var i = 0; i < data.pageInfo.navigatepageNums.length; i++) {
                    var pageNumber = data.pageInfo.navigatepageNums[i];
                    var li;
                    if (pageNumber == data.pageInfo.pageNum) {
                        li = '<li class="active"><a href="${path}/index.jsp?pageNum=' + pageNumber + '">' + pageNumber + '</a></li>';
                    } else {
                        li = '<li><a href="${path}/index.jsp?pageNum=' + pageNumber + '">' + pageNumber + '</a></li>';
                    }
                    lis += li;
                }

                //下一页
                var afterPageNum = data.pageInfo.pageNum + 1 > data.pageInfo.pages ? data.pageInfo.pages : data.pageInfo.pageNum + 1;
                var afterPageLi = '<li>\n' +
                    '                    <a href="${path}/index.jsp?pageNum=' + afterPageNum + '"\n' +
                    '                       aria-label="Next">\n' +
                    '                        <span aria-hidden="true">&raquo;</span>\n' +
                    '                    </a>\n' +
                    '                </li>';

                //尾页
                var lastPageLi = '<li><a href="${path}/index.jsp?pageNum=' + data.pageInfo.pages + '">尾页</a></li>';

                lis += afterPageLi;
                lis += lastPageLi;

                $("#page_nav").html(lis);
            }
        }

        //弹出模态框之前清空表单数据和新增的表单样式  jquery没有reset()方法，DOM对象有
        function reset_form(ele) {
            //清空表单数据
            $(ele)[0].reset();
            //清空表单样式
            $(ele).find("*").removeClass("has-success has-error glyphicon-ok glyphicon-remove");
            $(ele).find(".help-block").text("");

        }

        //添加按钮调用添加员工模态框
        function openAddEmpModal() {
            //弹出模态框之前清空表单数据和新增的表单样式  jquery没有reset()方法，DOM对象有
            reset_form("#addEmpForm");
            //模态框弹出之前查出部门信息，显示在下拉列表中
            //Ajax显示部门信息
            show_deptName_info("#add_deptName");

            $("#empAddModal").modal({
                backdrop: "static"
            });
        };

        //Ajax显示部门信息
        function show_deptName_info(ele) {
            $.post("${path}/department/getAllDept", {}, function (msg) {
                var nodes = '';
                for (var i = 0; i < msg.data.allDept.length; i++) {
                    var dept = msg.data.allDept[i];
                    var node = '<option value="' + dept.deptId + '">' + dept.deptName + '</option>';
                    nodes += node;
                }
                $(ele).html(nodes);
            });
        }

        //校验员工姓名
        function checkEmpName() {
            //1.定义正则表达式 不可全为空格和换行，允许字符前面和后面为空
            var pattern = /^[\s\S]*.*[^\s][\s\S]*$/;
            //2.获取员工姓名
            var deptName = $("#empName").val();
            //3.判断 给出提示信息
            var flag = pattern.test(deptName);
            if (flag) {
                //合法时校验用户名是否存在
                checkempNameIsExist();
            } else {
                //不合法
                show_validate_msg("#empName", "error", "员工姓名不能为空");
            }

            return flag;
        }

        //校验员工邮箱
        function checkEmail() {
            //1.定义正则表达式
            var pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
            //2.获取员工姓名
            var email = $("#email").val();
            //3.判断 给出提示信息
            var flag = pattern.test(email);
            if (flag) {
                //合法
                show_validate_msg("#email", "success", "");
            } else {
                //不合法
                show_validate_msg("#email", "error", "邮箱格式不正确");
            }

            return flag;
        }

        //显示校验结果的提示信息
        function show_validate_msg(ele, status, msg) {
            //清除之前添加样式
            $(ele).parent().removeClass("has-success has-error");
            $(ele).next("span").next("span").removeClass("glyphicon-ok glyphicon-remove");
            $(ele).next("span").text;

            if ("success" == status) {
                $(ele).parent().addClass("has-success");
                $(ele).next("span").text(msg);
                $(ele).next("span").next("span").addClass("glyphicon-ok");
                $(ele).next("span").next("span").next("span").text("(success)");
            } else if ("error" == status) {
                $(ele).parent().addClass("has-error");
                $(ele).next("span").text(msg);
                $(ele).next("span").next("span").addClass("glyphicon-remove");
                $(ele).next("span").next("span").next("span").text("(error)");
            }
        }

        //当某一个组件失去焦点时，调用与之对应的校验方法
        $(function () {
            //当某一个组件失去焦点时，调用与之对应的校验方法
            $("#empName").blur(checkEmpName);
            $("#email").blur(checkEmail);

        });

        //校验用户名是否存在
        function checkempNameIsExist() {
            //获取用户名的值
            var empName = $("#empName").val();
            //发送Ajax请求
            $.get("${path}/employee/checkEmpName", {empName: empName}, function (msg) {
                if (msg.code == 100) {
                    //给保存按钮加一个自定义属性ajax_status
                    $("#addEmpBtn").attr("ajax_status", "success");
                    //没有该员工
                    show_validate_msg("#empName", "success", "");
                } else if (msg.code == 200) {
                    //给保存按钮加一个自定义属性ajax_status
                    $("#addEmpBtn").attr("ajax_status", "error");
                    //有员工名已存在，请换一个
                    show_validate_msg("#empName", "error", "员工名已存在，请换一个");
                }
            });
        }

        //保存员工
        function addEmp() {
            //校验用户名和邮箱是否合法
            // alert(!(checkEmpName() && checkEmail()));
            if (!(checkEmpName() && checkEmail())) {
                return false;
            }

            // alert($("#addEmpBtn").attr("ajax_status") == "error");
            //判断保存按钮自定义属性ajax_status的值
            if ($("#addEmpBtn").attr("ajax_status") == "error") {
                return false;
            }

            //都合法，发送Ajax请求保存员工
            $.post("${path}/employee/emp", $("#addEmpForm").serialize(), function (msg) {
                if (msg.code == 200) {
                    //显示失败信息  JSR303校验（后端）
                    // console.info(msg);
                    if (msg.data.errorFields.empName != undefined) {
                        show_validate_msg("#empName", "error", msg.data.errorFields.empName);
                    }
                    if (msg.data.errorFields.email != undefined) {
                        show_validate_msg("#email", "error", msg.data.errorFields.email);
                    }
                } else if (msg.code == 100) {
                    // alert(msg.msg);
                    //1.关闭模态框
                    $('#empAddModal').modal('hide');
                    //2.来到最后一页，显示刚保存的数据
                    showPage(totalPageNum);
                }

            })
        }

        //打开修改员工模态框
        //1.我们是按钮创建之前就绑定了click，所以绑定不上。
        // 解决方法： （1）可以在创建按钮的时候就绑定  （2）绑定点击 on()
        //jquery新版本没有live ，使用on代替
        $(document).on("click", ".editEmp", function () {

            //0.获得部门信息
            show_deptName_info("#update_deptName");

            //1.获得员工信息
            //1.1获取员工id
            var empId = $(this).attr("edit_emp_id");
            //给更新按钮添加edit_emp_id属性 值为empId
            $("#updateEmpBtn").attr("edit_emp_id", empId);

            getEmpByEmpId(empId);

            //打开修改模态框
            $("#empUpdateModal").modal({
                backdrop: "static"
            });
        });

        //根据员工ID获取员工信息
        function getEmpByEmpId(empId) {
            $.get("${path}/employee/emp/" + empId, {}, function (msg) {
                $("#update_empName").val(msg.data.emp.empName);
                $("#update_email").val(msg.data.emp.email);
                /*$("input[name='gender']").each(function () {
                    if ($(this).val() == msg.data.emp.gender){
                        this.checked = true;
                    }else {
                        this.checked = false;
                    }
                })*/
                $("input[name='gender']").val([msg.data.emp.gender]);  //val([]) 会自动选择
                $("#update_deptName").val([msg.data.emp.dId]);
            })
        }

        //我们是按钮创建之前就绑定了click，所以绑定不上。
        /* $("#editEmp").click(function () {
             //打开修改模态框
             $("#empUpdateModal").modal({
                 backdrop: "static"
             });
         });*/

        //修改员工
        function updateEmp() {
            //校验邮箱

            //1.定义正则表达式
            var pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
            //2.获取员工姓名
            var email = $("#update_email").val();
            //3.判断 给出提示信息
            var flag = pattern.test(email);
            if (flag) {
                //合法
                show_validate_msg("#update_email", "success", "");
            } else {
                //不合法
                show_validate_msg("#update_email", "error", "邮箱格式不正确");
                return false;
            }


            //发送ajax请求修改员工
            $.ajax({
                url:"${path}/employee/emp/"+$("#updateEmpBtn").attr("edit_emp_id"),
                // data:$("#updateEmpForm").serialize()+"&_method=PUT",
                // type:"POST",
                //web.xml定义了HttpPutFormContentFilter过滤器直接发送PUT请求
                data:$("#updateEmpForm").serialize(),
                type:"PUT",
                success:function (msg) {
                    // alert(msg.msg);
                    //1.关闭模态框
                    $('#empUpdateModal').modal('hide');
                    //2.来到当前页，显示刚保存的数据
                    showPage(currentPage);
                }
            });
        }

        //删除员工
        function delEmp(empId,obj) {
            //获取想要删除员工姓名
            var empName = $(obj).parents("tr").find("td:eq(2)").text();
            // alert(empName);
            if(window.confirm("确定删除【"+empName+"】吗？")){
                $.ajax({
                    url:"${path}/employee/emp/"+empId,
                    data:"_method=DELETE",
                    type:"POST",
                    success:function (msg) {
                        //删除成功跳转回当前页
                        showPage(currentPage);
                    }
                })
            }
        }
        
        //删除选中的所有元素
        function delSelectEmp() {
            //遍历选中的
            var empNames = "";
            //选中员工id拼接的字符串ids
            var ids = "";
            $.each($("input[name='check']:checked"),function () {
                empNames += $(this).parents("tr").find("td:eq(2)").text() + ",";
                ids += $(this).parents("tr").find("td:eq(1)").text() + "-";
            });
            empNames = empNames.substring(0,empNames.length-1);
            ids = ids .substring(0,ids.length-1);
            // alert(empNames);
            // alert(ids);
            if(confirm("确定删除【"+empNames+"】吗？")){
                $.ajax({
                url:"${path}/employee/emp/"+ids,
                data:"_method=DELETE",
                type:"DELETE",
                success:function () {
                    if(currentPage==totalPageNum){
                        currentPage -= 1;
                    }
                    showPage(currentPage);
                }
            })
            }

        }

    </script>
</head>
<body>

<!-- 员工添加的模态框 -->
<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">添加员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="addEmpForm">
                    <div class="form-group">
                        <label for="empName" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10 has-feedback">
                            <input type="text" class="form-control" id="empName" name="empName"
                                   aria-describedby="checkEmpNameStatus" placeholder="empName">
                            <span class="help-block"></span>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <span id="checkEmpNameStatus" class="sr-only"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10 has-feedback">
                            <input type="email" class="form-control" id="email" name="email"
                                   aria-describedby="checkEmailStatus" placeholder="email@qq.com">
                            <span class="help-block"></span>
                            <span class="glyphicon form-control-feedback" aria-hidden="true"></span>
                            <span id="checkEmailStatus" class="sr-only"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" value="M" checked="checked"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <select class="form-control" id="add_deptName" name="dId"></select>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label"></label>
                        <div class="col-sm-4">
                            <input type="reset" class="btn btn-primary" value="重置">
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="addEmpBtn" class="btn btn-primary" onclick="addEmp();">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 员工修改的模态框 -->
<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">修改员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal" id="updateEmpForm">
                    <div class="form-group">
                        <label for="empName" class="col-sm-2 control-label">empName</label>
                        <div class="col-sm-10 has-feedback">
                            <input type="text" class="form-control" id="update_empName" name="empName"
                                   aria-describedby="checkEmpNameStatus" readonly placeholder="empName">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="email" class="col-sm-2 control-label">email</label>
                        <div class="col-sm-10 has-feedback">
                            <input type="email" class="form-control" id="update_email" name="email"
                                   aria-describedby="checkEmailStatus" placeholder="email@qq.com">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">gender</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="gender" value="M"> 男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="gender" value="F"> 女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">deptName</label>
                        <div class="col-sm-4">
                            <select class="form-control" id="update_deptName" name="dId"></select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="updateEmpBtn" class="btn btn-primary" onclick="updateEmp();">更新</button>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <h1>SSM_CRUD</h1>

    <div style="float: right; margin-top:50px;margin-bottom: 10px">
        <button type="button" class="btn btn-primary" id="emp_add_modal_btn" onclick="openAddEmpModal();">添加</button>
        <button class="btn btn-danger" onclick="delSelectEmp();">删除选中</button>
    </div>

    <table class="table table-striped">
        <thead>
        <tr>
            <th><input type="checkbox" id="checkAll"/></th>
            <th>编号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>邮箱</th>
            <th>部门编号</th>
            <th>部门名称</th>
            <th colspan="2">操作</th>
        </tr>
        </thead>
        <tbody id="tbody">
        </tbody>
    </table>

    <div id="page_info"
         style=" float: left;margin-top: 40px;position:absolute;left:50%;transform: translate(-50%,-50%)">
    </div>
    <div style="float: right;margin: 60px">
        <nav aria-label="Page navigation">
            <ul class="pagination pagination-lg" id="page_nav">

            </ul>
        </nav>
    </div>

</div>


</body>
</html>

